package com.bmw.redis3.service.impl;

import com.bmw.redis3.base.RankResp;
import com.bmw.redis3.dao.ArticleDao;
import com.bmw.redis3.model.Article;
import com.bmw.redis3.service.RankService;
import com.bmw.redis3.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Service("rankService")
public class RankServiceImpl implements RankService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ArticleDao articleDao;

    @Override
    public List<RankResp> list() {
        String key = "rank:list";
        Set<ZSetOperations.TypedTuple<Object>> set = redisUtil.zrevrangeByScoreWithScores(key,0D,1000D);
        Iterator<ZSetOperations.TypedTuple<Object>> it = set.iterator();
        int rank = 1;
        List<RankResp> list = new ArrayList<>();
        while (it.hasNext()){
            ZSetOperations.TypedTuple<Object> e = it.next();
            RankResp resp = new RankResp();
            Article article = articleDao.selectByArticleName(e.getValue().toString());
            resp.setMessageName(article.getArticleName());
            resp.setLike(article.getVisits());
            resp.setRank(rank);
            list.add(resp);
            rank++;
        }
        return list;
}
}
